package com.yizhang.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.yizhang.io.Resources;
import com.yizhang.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @Author: yi.zhang
 * @CreateTime: 2025-05-27 15:04:33
 * @Description: 解析sqlMapConfig.xml
 */
public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 用dom4j解析xml文件
     * @param inputStream
     * @return
     */
    public Configuration parse(InputStream inputStream) throws DocumentException {
        // 获取property标签
        Document document = new SAXReader().read(inputStream);
        Element root = document.getRootElement();
        List<Element> list = root.selectNodes("//property");

        // 获取数据库相关配置
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        // 数据库配置放入configuration
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(properties.getProperty("driverClassName"));
        dataSource.setUrl(properties.getProperty("url"));
        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(dataSource);

        // 解析mapper.xml
        List<Element> elementList = root.selectNodes("//mapper");
        for (Element element : elementList) {
            String resource = element.attributeValue("resource");
            InputStream resourceAsSteam = Resources.getResourceAsSteam(resource);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsSteam);
        }
        return configuration;
    }
}
